package com.eendtech.androidthreadtest;

import android.util.Log;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 网络访问工具类
 * Created by Seale on 2018/11/12.
 */

public class OkHttpUtils {
    private static final String TAG = "OkHttpUtils";
    private String url = "" ;
    /**
     *  可以对全局进行url地址的初始化,保存同一个url地址
     * @param url 对url地址进行赋值
     */
    public OkHttpUtils(String url) {
        this.url = url;
    }

    /**
     * 可以不用进行初始化,直接在方法中初始化url地址
     */
    public OkHttpUtils(){}

    /**
     * 异步GET请求
     * @param url 当前请求的url地址
     * @param asynGet 接口
     *            Asynchronous Get
     */
    public void getAsynOkHttp(String url, final AsynGet asynGet){
        final OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = client.newCall(request);
        //提交异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: 失败");
                asynGet.onFail(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse: 成功响应");
                asynGet.onResponse(call, response);
            }
        });
    }
    public void getAsynOkHttp(final AsynGet asynGet){
        if (this.url == null || this.url == "" || this.url == " "){
            new NullPointerException();
            return;
        }
        String url = this.url;
        getAsynOkHttp(url,asynGet);
    }

    /**
     * 同步get请求
     * @param url 当前请求的url地址
     * @param synGet 接口
     */
    public void getSynOkHttp(String url, final SynGet synGet){
        final OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        final Call call = client.newCall(request);
        //开启线程进行同步get请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.d(TAG, "run: 线程启动");
                    Response response = call.execute();
                    synGet.onResponse(call,response);
                } catch (IOException e) {
                    e.printStackTrace();
                    synGet.onFail(call,e);
                }
            }
        }).start();

    }
    public void getSynOkHttp(SynGet synGet){
        if (this.url == null || this.url == "" || this.url == "\n "){
            new NullPointerException();
            return;
        }
        String url = this.url;
        getSynOkHttp(url,synGet);
    }



}
